package com.company.ems.filter;

import com.company.ems.model.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 拦截所有受保护资源：仪表盘、员工管理相关页面和Servlet
@WebFilter(filterName = "AuthenticationFilter", urlPatterns = {
        "/dashboard.jsp",
        "/employee/*",
        "/EmployeeServlet",
        "/DashboardServlet"
})
public class AuthenticationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 转换为Http请求/响应对象，获取Session
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        // 检查Session中是否有登录用户（与LoginServlet存入的key一致）
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            // 未登录：设置错误提示，转发到登录页
            req.setAttribute("errorMsg", "请先登录！");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return; // 终止后续流程，避免访问受保护资源
        }

        // 已登录：放行请求，继续访问目标资源
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}